//package org.dragonnova.meetingapp.app.service;
//
//import android.app.Service;
//import android.content.BroadcastReceiver;
//import android.content.Context;
//import android.content.Intent;
//import android.content.IntentFilter;
//import android.content.SharedPreferences;
//import android.net.ConnectivityManager;
//import android.net.NetworkInfo;
//import android.net.wifi.WifiInfo;
//import android.net.wifi.WifiManager;
//import android.os.Binder;
//import android.os.Bundle;
//import android.os.IBinder;
//import android.os.Parcelable;
//import android.os.SystemClock;
//import android.provider.Settings;
//import android.text.TextUtils;
//import android.util.Log;
//
//import org.dragonnova.meetingapp.R;
//import org.dragonnova.meetingapp.model.bean.DeviceInfo;
//import org.dragonnova.meetingapp.model.bean.MeetingInfo;
//import org.dragonnova.meetingapp.model.bean.VoiceInfo;
//import org.dragonnova.meetingapp.utils.Constants;
//import org.dragonnova.meetingapp.utils.ContentResolverUtil;
//import org.dragonnova.meetingapp.utils.LogUtil;
//import org.dragonnova.meetingapp.utils.PromptUtil;
//import org.dragonnova.meetingapp.utils.WifiAutoConnectUtil;
//
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.net.InetAddress;
//import java.net.InetSocketAddress;
//import java.net.MulticastSocket;
//import java.net.SocketAddress;
//import java.net.SocketException;
//import java.net.SocketTimeoutException;
//import java.util.TreeSet;
//import java.util.concurrent.LinkedBlockingQueue;
//
///**
// * @author songxy
// *         Created at 2015/12/7 10:36
// *         Email: thinkdata@163.com
// *         用于管理WIFI网络入口、服务端通信、数据传输
// */
//public class WIFIService extends Service {
//    public final static String SETTING = "SETTINGS";
//
//    private final static String TAG = WIFIService.class.getName();
//    /**
//     * 用于广播：监听，连接中，已连接，断开连接
//     */
//    public final static String KEY_GROUP_CONNECTING_STATUS = "CONNECTING";
//    public final static String KEY_GROUP_CONNECTED_STATUS = "CONNECTED";
//    public final static String KEY_GROUP_DISCONNECT_STATUS = "DISCONNECT";
//    /**
//     * 应答机制 允许录音，不允许录音，服务端已经停止
//     */
//    public final static String KEY_VOICE_RESPONSE_PERMIT = "PERMIT";
//    public final static String KEY_VOICE_RESPONSE_PREVENT = "PREVENT";
//    public final static String KEY_VOICE_RESPONSE_FINISH = "FINISH";
//    /**
//     * 用于组网状态标识：监听，连接中，已经连接，断开连接，没有网络状态
//     */
//    public final static int GROUP_WIFI_NOT_CORRECT_STATUS = 0;
//    public final static int GROUP_CONNECTING_STATUS = 1;
//    public final static int GROUP_CONNECTED_STATUS = 2;
//    public final static int GROUP_DISCONNECTED_STATUS = 3;
//    /**
//     * 用于组网状态标识：未开启，开启，未连接，连接中，已连接，连接断开
//     */
//    public final static int WIFI_DISABLED_STATUS = 0;
//    public final static int WIFI_ENABLED_STATUS = 1;
//    public final static int WIFI_CONNECTING_STATUS = 2;
//    public final static int WIFI_CONNECTED_STATUS = 3;
//    public final static int WIFI_DISCONNECTED_STATUS = 4;
//    public final static int WIFI_INCORRECT_STATUS = 5;
//    public final static int WIFI_CORRECT_STATUS = 6;
//    /**
//     * 服务端语音改变成功
//     */
//    public final static String KEY_LANGUAGE_CHANGED = "LANGUAGE_CHANGE_SUCESS";
//
//    public final static String KEY_HANDLER_ORG_VOICE_TEXT_ERROR = "org.dragonnova.meetingapp.action.ORG_VOICE_TEXT_ERROR";
//    public final static String INTENT_TRANSFER_VOICE_DATA = "TRANSFER_VOICE_DATA";
//    public final static String KEY_HANDLER_ORG_VOICE_DATA = "org.dragonnova.meetingapp.action.ORG_VOICE_DATA";
//
//    public final static String KEY_HANDLER_DEVICE_INFO = "org.dragonnova.meetingapp.action.HANDLER_DEVICE_INFO";
//    public final static String KEY_HANDLER_WIFI_CONNECT = "org.dragonnova.meetingapp.action.HANDLER_WIFI_CONNECT";
//    public final static String KEY_HANDLER_MEETING_CREATED = "org.dragonnova.meetingapp.action.HANDLER_MEETING_CREATED";
//
//    private static final int KEY_ACTION_GROUP_NO_JOIN = 0xBB;
//    private static final int KEY_ACTION_GROUP_ALLOW_JOIN = 0xAA;
//    private static final int KEY_ACTION_GROUP_JOINED = 0xDD;
//    private static final byte KEY_ACTION_GROUP_CONFIRM_1 = (byte) 0xEE;
//    private static final byte KEY_ACTION_GROUP_JOIN_REQUEST = (byte) 0xCC;
//    private static final byte KEY_ACTION_GROUP_CONFIRM_2 = (byte) 0xFF;
//    private static final byte KEY_ACTION_TRANSFER_VOICE_DATA = (byte) 0x10;
//    private static final byte KEY_ACTION_GROUP_EXIT = (byte) 0x99;
//    private static final int KEY_ACTION_GROUP_CONNECTED_REQUEST = 0x01;
//    private static final int KEY_ACTION_GROUP_CONNECTED_RESPONSE = 0x02;
//    private static final int KEY_ACTION_GROUP_CHANGE_LANGUAGE = 0x31;
//    private static final int KEY_ACTION_GROUP_CHANGE_LANGUAGE_COMPLETE = 0x32;
//    private static final int KEY_ACTION_DEVICE_REQUEST = 0x35;
//    private static final int KEY_ACTION_DEVICE_RESPONSE = 0x36;
//    private static final int KEY_ACTION_DEVICE_CHANGE_REQUEST = 0x37;
//    private static final int KEY_ACTION_DEVICE_CHANGE_RESPONSE_SUCCESS = 0x38;
//    private static final int KEY_ACTION_CREATE_MEETING = 0x19;
//    private static final int KEY_ACTION_CREATE_MEETING_RESPONSE = 0x18;
//    private static final int KEY_ACTION_VOICE_REQUEST_START = 0x03;
//    private static final int KEY_ACTION_VOICE_REQUEST_STOP = 0x04;
//    private static final int KEY_ACTION_VOICE_REQUEST_PERSIST = 0x08;
//    private static final int KEY_ACTION_VOICE_RESPONSE_PERMIT = 0x05;
//    private static final int KEY_ACTION_VOICE_RESPONSE_PREVENT = 0x06;
//    private static final int KEY_ACTION_VOICE_RESPONSE_FINISH = 0x07;
//    private static final int KEY_ACTION_VOICE_RESPONSE_PERSIST = 0x09;
//
//    private static final String KEY_ACTION_EXIT = "EXIT";
//    private static final String KEY_ACTION_JOIN_REQUEST = "REQUEST";
//    /**
//     * 多播地址
//     */
//    private final static String MULTICAST_NETWORK_IP = "239.255.255.250";
//    /**
//     * 多播端口
//     */
//    private final static int MULTICAST_NETWORK_PORT = 25221;
//    /**
//     * 本地UDP通信端口
//     */
//    private final static int CLIENT_SOCKET_PORT = 24535;
//    /**
//     * 本地UDP通信端口
//     */
//    private final static int CLIENT_SOCKET_PORT_BEAT = 24357;
//    /**
//     * 本地UDP通信端口
//     */
//    private final static int CLIENT_SOCKET_PORT_VOICE_REQUEST = 24355;
//    /**
//     * UDP通信端口
//     */
//    private final static int SERVER_SOCKET_PORT = 30002;
//    /**
//     * UDP通信端口
//     */
//    private final static int SERVER_SOCKET_PORT_BEAT = 30001;
//    /**
//     * UDP通信端口
//     */
//    private final static int SERVER_SOCKET_PORT_VOICE_REQUEST = 30000;
//    /**
//     * 队列上限
//     */
//    private final static int VOICE_MAX_QUEUE_SIZE = 200;
//
//
//    private static final String SSID = "SSID";
//    /**
//     * 多播线程
//     */
//    public MulticastSendThread multicastSendWorker;
//    /**
//     * 组网接收线程
//     */
//    public MulticastRecThread multicastRecWorker;
//    /**
//     * 当前wifi组网状态
//     */
//    public int mCurrentGroupStatus;
//    /**
//     * 本地活动网络状态
//     */
//    private int mCurrentWifiStatus;
//    /**
//     * 服务端的音频流
//     */
//    public byte[] serverVoiceData;
//    /**
//     * 用于UDP多播组网
//     */
//    private AppSocket mMulticastSocket;
//    /**
//     * 用于组网状态的管理
//     */
//    private LinkedBlockingQueue<Integer> netObserverQueue = new LinkedBlockingQueue<>(VOICE_MAX_QUEUE_SIZE);
//    /**
//     * 用于应答机制的队列
//     */
//    private LinkedBlockingQueue<Integer> voiceReqQueue = new LinkedBlockingQueue<>(VOICE_MAX_QUEUE_SIZE);
//    /**
//     * Udp通信，用于语音信息的传输
//     */
//    private AppSocket mUdpSocket;
//    /**
//     * Udp通信，用于间隔时间监听网络连接情况
//     */
//    private AppSocket mBeatSocket;
//    /**
//     * Udp通信，向服务器请求是否可以说话
//     */
//    private AppSocket mVoiceReqSocket;
//    /**
//     * 组网包发送间隔时间
//     */
//    private int WIFI_GROUP_SEND_THREAD_INTERVAL_TIME;
//    private int WIFI_GROUP_SEND_THREAD_INTERVAL_TIME_1;
//    /**
//     * 网络状态广播接收
//     */
//    private NetReceiver mNetReceiver = new NetReceiver();
//    /**
//     * UDP语音接收和发送线程
//     */
//    public UdpWorker udpWorker;
//    /**
//     * UDP语音接收和发送线程
//     */
//    public BeatWorker beatWorker;
//
//    public VoiceReqWorker voiceReqWorker;
//    /**
//     * 组播IP
//     */
//    private InetSocketAddress mMulticastInetAddr;
//    /**
//     * 设备ID
//     */
//    private String mDeviceId;
//    /**
//     * 蓝牙设备名称
//     */
//    private String btName;
//    /**
//     * UDP服务端IP
//     */
//    private String UDP_SERVER_IP;
//    /**
//     * 本地
//     */
//    private String UDP_CLIENT_IP;
//    /**
//     * 用于管理WIFI网络入口
//     */
//    private MainThread mainWorker;
//    /**
//     * 监听网络
//     */
//    private WifiObserverThread wifiObserver;
//    /**
//     * 多播锁
//     */
//    private WifiManager.MulticastLock multicastLock;
//    /**
//     * wifi管理
//     */
//    private WifiManager mWifiManager;
//    /**
//     * 网络连接管理
//     */
//    private ConnectivityManager mConnectivityManager;
//    /**
//     * 网络信息
//     */
//    private NetworkInfo networkInfo;
//    /**
//     * Preferences
//     */
//    private SharedPreferences mPreferences;
//    /**
//     * service binder
//     */
//    private WifiBinder wifiBinder = new WifiBinder();
//    /**
//     * 设备地址
//     */
//    private SocketAddress mServerAddr;
//
//    private char mLanguage;
//    /**
//     * 语音接收处理
//     */
//    private WIFIObserver mWifiObserver;
//    /**
//     * _(:3 」∠)_固定ip，测试
//     */
//    private String UNIQUE_SSID = "G105-3";
//    private String UNIQUE_PASSWORD = "11111111";
//
//    /*private String UNIQUE_SSID = "development";
//    private String UNIQUE_PASSWORD = "12345678";*/
//
//
//    TreeSet<DeviceInfo> DevicesInfos = new TreeSet<>();
//
//    private String hostName = "测试1号";
//
//    private MeetingInfo mMeetingInfo = new MeetingInfo();
//
//
//    public class WifiBinder extends Binder {
//
//        /**
//         * 发送语音包
//         */
//        public void sendVoiceData(VoiceInfo voiceInfo) {
//            voiceInfo.setUserId(hostName);
//            try {
//                WIFIService.this.udpWorker.sendPacketData(voiceInfo.encode());
//            } catch (IOException | NullPointerException e) {
//                Log.e(TAG, "wifiServer Send Udp Package Error. " + e.getMessage());
//            }
//        }
//
//        public void sendExit() {
//            sendExitPacket();
//        }
//
//        public boolean setWifiInfo(String ssid, String passwd) {
//            updateWifiInfo(ssid, passwd, "WAP");
//            return true;
//        }
//
//        public void searchDevices() {
//            DevicesInfos.clear();
//
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//
//                    LogUtil.eee("mCurrentGroupStatus === " + mCurrentWifiStatus);
//                    if (mCurrentWifiStatus == WIFI_CORRECT_STATUS && isMulticastSocketExisted()) {
//                        AppUDPPacket outPacket = new AppUDPPacket();
//                        outPacket.setPacketData(new byte[0]);
//                        outPacket.setPacketDataLength(0);
//                        outPacket.setSocketAddress(mMulticastInetAddr);
//                        outPacket.setAction(new byte[]{KEY_ACTION_DEVICE_REQUEST});
//                        for (int i = 0; i < 1; i++) {
//                            LogUtil.eee("seach devices through multi cast socket");
//                            sendMulticastPacket(outPacket);
//                            SystemClock.sleep(500);
//                        }
//                    }
//                }
//            }).start();
//        }
//
//        public void renameDevice(final DeviceInfo info) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    if (mCurrentWifiStatus == WIFI_CORRECT_STATUS && isMulticastSocketExisted()) {
//                        byte[] msg = info.encode();
//                        AppUDPPacket outPacket = new AppUDPPacket();
//                        outPacket.setPacketDataLength(msg.length);
//                        outPacket.setPacketData(msg);
//                        outPacket.setSocketAddress(mMulticastInetAddr);
//                        outPacket.setAction(new byte[]{KEY_ACTION_DEVICE_CHANGE_REQUEST});
//                        for (int i = 0; i < 1; i++) {
//                            sendMulticastPacket(outPacket);
//                            SystemClock.sleep(200);
//                        }
//                    }
//                }
//            }).start();
//        }
//
//        /**
//         * 语音应答线程发送语音输入请求
//         */
//        public void requestVoiceStart() {
//            if (mCurrentGroupStatus == GROUP_CONNECTED_STATUS) {
//                try {
//                    voiceReqQueue.put(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            } else {
//                Intent intent = new Intent();
//                intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_PREVENT);
//                sendBroadcast(intent);
//            }
//        }
//
//        /**
//         * 语音应答线程停止发送语音正在输入的消息，且发送停止消息
//         */
//        public void requestVoiceStop() {
//            if (mCurrentGroupStatus == GROUP_CONNECTED_STATUS) {
//                try {
//                    voiceReqQueue.put(2);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                voiceReqWorker.requestStop();
//            } else {
//                Intent intent = new Intent();
//                intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_FINISH);
//                sendBroadcast(intent);
//            }
//        }
//
//        public void startGroup() {
//            synchronized (mainWorker) {
//                mainWorker.notify();
//            }
//        }
//
//        public void stopGroup() {
//            sendExit();
//            stopAllThreadAndSocket();
//        }
//
//        /**
//         * 提供Service对象
//         */
//        public WIFIService getService() {
//            return WIFIService.this;
//        }
//
//        public void createMeeting(final MeetingInfo meetingInfo) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        WIFIService.this.udpWorker.sendMeetingData(meetingInfo.encode());
//                    } catch (IOException | NullPointerException e) {
//                        Log.e(TAG, "wifiServer Send Udp Package Error. " + e.getMessage());
//                    }
//                }
//            }).start();
//        }
//
//        public void resetMeeting(final MeetingInfo meetingInfo) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        meetingInfo.setSerial(mMeetingInfo.getSerial());
//                        WIFIService.this.udpWorker.sendMeetingData(meetingInfo.encode());
//                    } catch (IOException | NullPointerException e) {
//                        Log.e(TAG, "wifiServer Send Udp Package Error. " + e.getMessage());
//                    }
//                }
//            }).start();
//        }
//
//        public MeetingInfo getMeetingInfo() {
//            return mMeetingInfo;
//        }
//
//        /**
//         * 改变wifiservice中的语音设置
//         */
//        public void changeLocalLanguage(boolean isCH2EN) {
//            if (isCH2EN) {
//                mLanguage = getString(R.string.language_c).charAt(0);
//            } else {
//                mLanguage = getString(R.string.language_e).charAt(0);
//            }
//        }
//
//        /**
//         * 发送到服务端改变服务端deviceinfo中的语言标志
//         */
//        public void changeServerLanguage(char language) {
//            byte[] dataStr = getDeviceInfoPacketByLanguage(language);
//            final AppUDPPacket outPacket = new AppUDPPacket();
//            outPacket.setPacketDataLength(dataStr.length);
//            outPacket.setPacketData(dataStr);
//            outPacket.setSocketAddress(mMulticastInetAddr);
//            outPacket.setAction(new byte[]{KEY_ACTION_GROUP_CHANGE_LANGUAGE});
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    sendMulticastPacket(outPacket);
//                }
//            }).start();
//        }
//
//        public void setMeetingId(int id) {
//            mMeetingInfo.setId(id);
//        }
//    }
//
//    @Override
//    public void onCreate() {
//        super.onCreate();
//
//        LogUtil.eee("onCreate============================");
//        //初始化参数
//        initParam();
//        //加入网络
//        //joinWifi();
//        //注册广播
//        registerReceiver(mNetReceiver, getFilter());
//        //启动网络线程，组网、服务SOCKET初始化
//        mainWorker = new MainThread();
//        mainWorker.start();
//        //启动网络观察线程
//        wifiObserver = new WifiObserverThread();
//        wifiObserver.start();
//    }
//
//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//        return Service.START_STICKY;
//    }
//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        LogUtil.eee("onDestroy============================");
//        multicastUnLock();
//        try {
//            unregisterReceiver(mNetReceiver);
//        } catch (IllegalArgumentException e) {
//            Log.e(TAG, "onDestroy Error: " + e.getMessage());
//        }
//        stopAllThreadAndSocket();
//
//        if (mainWorker != null) {
//            mainWorker.close();
//            mainWorker.setFlag(false);
//            mainWorker.interrupt();
//        }
//        if (wifiObserver != null) {
//            wifiObserver.setFlag(false);
//            wifiObserver.interrupt();
//        }
//    }
//
//    /**
//     * 销毁除了主线程和网络监听线程外的其他线程
//     */
//    private void stopAllThreadAndSocket() {
//        if (multicastSendWorker != null) {
//            multicastSendWorker.setFlag(false);
//            multicastSendWorker.interrupt();
//            multicastSendWorker = null;
//        }
//        if (multicastRecWorker != null) {
//            multicastRecWorker.setFlag(false);
//            multicastRecWorker.interrupt();
//            multicastRecWorker = null;
//        }
//        if (udpWorker != null) {
//            udpWorker.setFlag(false);
//            udpWorker.interrupt();
//            udpWorker = null;
//        }
//        if (beatWorker != null) {
//            beatWorker.setFlag(false);
//            beatWorker.interrupt();
//            beatWorker = null;
//        }
//        if (voiceReqWorker != null) {
//            voiceReqWorker.setFlag(false);
//            voiceReqWorker.interrupt();
//            voiceReqWorker = null;
//        }
//        if (mMulticastSocket != null) {
//            mMulticastSocket.close();
//            mMulticastSocket = null;
//        }
//        if (mUdpSocket != null) {
//            mUdpSocket.close();
//            mUdpSocket = null;
//        }
//        if (mBeatSocket != null) {
//            mBeatSocket.close();
//            mBeatSocket = null;
//        }
//        if (mVoiceReqSocket != null) {
//            mVoiceReqSocket.close();
//            mVoiceReqSocket = null;
//        }
//    }
//
//    @Override
//    public boolean onUnbind(Intent intent) {
//        LogUtil.eee("onUnbind=================================");
//        return super.onUnbind(intent);
//    }
//
//    @Override
//    public IBinder onBind(Intent intent) {
//        LogUtil.eee("onBind=================================");
//        return wifiBinder;
//    }
//
//    @Override
//    public void onRebind(Intent intent) {
//        LogUtil.eee("WIFIService onRebind=============================");
//        super.onRebind(intent);
//    }
//
//    /**
//     * 初始化变量
//     */
//    private void initParam() {
//        // 数据
//        mPreferences = getSharedPreferences(SETTING, MODE_PRIVATE);
//        // ConnectivityManager主要管理和网络连接相关的操作
//        // [type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: "G105", roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false]
//        mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
//        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//        // 5baa6b96a2e46276
//        mDeviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
//        // HUAWEI P7-L00
//        //btName = BluetoothAdapter.getDefaultAdapter().getName();
//        // 5000
//        WIFI_GROUP_SEND_THREAD_INTERVAL_TIME = getResources().getInteger(R.integer.wifi_group_thread_send_interval);
//        // 10000
//        WIFI_GROUP_SEND_THREAD_INTERVAL_TIME_1 = getResources().getInteger(R.integer.wifi_group_thread_send_interval_1);
//        //c:e
//        mLanguage = getString(R.string.language_c).charAt(0);
//        // 192.168.1.100/24
//        UDP_CLIENT_IP = SocketUtil.convertIntIpAddress(mWifiManager.getConnectionInfo().getIpAddress());
//        // 观察者，拿到网络数据之后发送给MainActivity进行合成
//        mWifiObserver = new WIFIObserver();
//    }
//
//    /**
//     * 添加WIFI,网络活动状态下才能建立组网和UDP线程
//     * 前提条件：
//     * 1. SSID和现有不等
//     * 2. SSID不存在,等待APP控制
//     */
//    private void joinWifi() {
//        NetworkInfo networkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//        //SSID: G105-2, BSSID: 30:fc:68:69:a1:04, MAC: cc:a2:23:36:10:a8, Supplicant state: COMPLETED, RSSI: -24, Link speed: 72Mbps, Frequency: 2462MHz, Net ID: 8, Metered hint: false, score: 100
//        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
//        //wifi是否未连接，数据服务要等到连接以后才能进行
//        if ((networkInfo.getState() == NetworkInfo.State.CONNECTED) && wifiInfo.getSSID() != null && (wifiInfo.getSSID().equalsIgnoreCase("\"" + UNIQUE_SSID + "\"") || wifiInfo.getSSID().equalsIgnoreCase(UNIQUE_SSID))) {
//            //192.168.1.100
//            UDP_CLIENT_IP = SocketUtil.convertIntIpAddress(mWifiManager.getConnectionInfo().getIpAddress());
//        } else {
//            if (!TextUtils.isEmpty(UNIQUE_SSID)) doWifiRefresh(UNIQUE_SSID, UNIQUE_PASSWORD, "WAP");
//        }
//    }
//
//    /**
//     * 修改WIFI信息
//     * 前提条件：
//     * 1. SSID和现有不等
//     * 2. SSID不存在
//     * 3. 修改密码
//     */
//    private void updateWifiInfo(String ssid, String passwd, String wifiKey) {
//        if (ssid == null || passwd == null) {
//            Log.d(TAG, "SSID OR PASSWORD IS NULL");
//        } else if (!TextUtils.isEmpty(ssid) && !TextUtils.isEmpty(passwd)) {
//            // 活动网络处于连接诶状态，且SSID相同或
//            UNIQUE_SSID = ssid;
//            UNIQUE_PASSWORD = passwd;
//            stopAllThreadAndSocket();
//            doWifiRefresh(ssid, passwd, wifiKey);
//        }
//    }
//
//    /**
//     * 刷新网络
//     */
//    private void doWifiRefresh(final String ssid, final String passwd, final String wifiKey) {
//        new WifiAutoConnectUtil(mWifiManager).connect(ssid, passwd, WifiAutoConnectUtil.WifiCipherType.WIFICIPHER_WPA);
//    }
//
//    /**
//     * 发送退出
//     */
//    private void sendExitPacket() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                if (isNetGroupConnected2()) {
//                    for (int i = 0; i < 5; i++) {
//                        sendMulticastPacket(getPacketByType(KEY_ACTION_EXIT));
//                    }
//                }
//            }
//        }).start();
//    }
//
//
//    // TODO: 2016/5/11 目前不用蓝牙来进行数据传输，所以设备的蓝牙地址为 00:00:00:00:00:00
//
//    private byte[] getDeviceInfoPacket() {
//        String ipAddr = SocketUtil.convertIntIpAddress(mWifiManager.getConnectionInfo().getIpAddress());
//        String wifiMacAddr = mWifiManager.getConnectionInfo().getMacAddress();
//        return new DeviceInfo(mDeviceId, "app", wifiMacAddr, ipAddr, btName, mLanguage, CLIENT_SOCKET_PORT).encode();
//    }
//
//    //DEVICEID|WIFIADDR|WIFIPORT|BTADDR|BTNAME|TIMESTAMP|L
//    private byte[] getDeviceInfoPacketByLanguage(char language) {
//        String ipAddr = SocketUtil.convertIntIpAddress(mWifiManager.getConnectionInfo().getIpAddress());
//        String wifiMacAddr = mWifiManager.getConnectionInfo().getMacAddress();
//        //String hostId, String hostName, String wifiMacAddr, String btMacAddr, String wifiAddr, String btName, char language, int port
//        return new DeviceInfo(mDeviceId, hostName, wifiMacAddr, "????", ipAddr, btName, language, CLIENT_SOCKET_PORT).encode();
//    }
//
//    /**
//     * 加锁
//     */
//    private synchronized void multicastLock() {
//        multicastLock = mWifiManager.createMulticastLock("GROUP LOCK");
//        multicastLock.acquire();
//    }
//
//    /**
//     * 解锁
//     */
//    private synchronized void multicastUnLock() {
//        if (multicastLock != null && multicastLock.isHeld())
//            multicastLock.release();
//    }
//
//    /**
//     * 解析发送组网包为设备信息
//     * **DEVICEID|WIFIADDR|WIFIPORT|BTADDR|BTNAME|TIMESTAMP|L**
//     */
//    public DeviceInfo parseDevicePacket(AppUDPPacket packet) {
//        DeviceInfo deviceInfo = null;
//        if (packet.getPacketDataLength() > 0) {
//            String msg = new String(packet.getPacketData());
//            deviceInfo = DeviceInfo.parse(msg);
//        }
//        return deviceInfo;
//    }
//
//    /**
//     * 发送多播通信包
//     */
//    private synchronized void sendMulticastPacket(AUDPPacket outPacket) {
//        if (isMulticastSocketExisted()) {
//            try {
//                mMulticastSocket.sendMsgToNetwork(outPacket);
//            } catch (IOException e) {
//                Log.e(TAG, " Send Packet Error: " + e.getMessage());
//            }
//        }
//    }
//
//    /**
//     * 是否组网
//     */
//    private boolean isNetGroupConnected() {
//        return UDP_SERVER_IP != null && mServerAddr != null
//                && mCurrentGroupStatus == GROUP_CONNECTED_STATUS;
//    }
//
//    private boolean isNetGroupConnected2() {
//        return UDP_SERVER_IP != null && mServerAddr != null;
//    }
//
//    /**
//     * 多播组网是否绑定本地端口
//     */
//    private boolean isMulticastSocketExisted() {
//        return mMulticastSocket != null && mMulticastSocket.isBound();
//    }
//
//    /**
//     * 根据类型生成本机信息通信包
//     */
//    private AUDPPacket getPacketByType(String type) {
//        byte[] dataStr = getDeviceInfoPacket();
//        AppUDPPacket outpacket = null;
//        if (type.equalsIgnoreCase(KEY_ACTION_EXIT)) {
//            outpacket = new AppUDPPacket();
//            outpacket.setAction(new byte[]{KEY_ACTION_GROUP_EXIT});
//        } else if (type.equalsIgnoreCase(KEY_ACTION_JOIN_REQUEST)) {
//            outpacket = new AppUDPPacket();
//            outpacket.setAction(new byte[]{KEY_ACTION_GROUP_JOIN_REQUEST});
//        }
//        if (outpacket != null) {
//            outpacket.setPacketDataLength(dataStr.length);
//            outpacket.setPacketData(dataStr);
//            outpacket.setSocketAddress(mMulticastInetAddr);
//        }
//        return outpacket;
//    }
//
//    private IntentFilter getFilter() {
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        return filter;
//    }
//
//    private class WifiObserverThread extends Thread {
//        private boolean waitFlag = true;
//        private int preMsg = 0;
//
//        @Override
//        public void run() {
//            // 联网且是WIFI网络状态下
//            while (waitFlag) {
//                try {
//                    int msg = netObserverQueue.take();
//                    if (preMsg != msg) {
//                        if (msg == 1) {
//                            synchronized (mainWorker) {
//                                //mainWorker.notify();
//                            }
//                        } else if (msg == 2) {
//                            stopAllThreadAndSocket();
//                            joinWifi();
//                        } else if (msg == 0) {
//                            stopAllThreadAndSocket();
//                            joinWifi();
//                        }
//                    }
//                    preMsg = msg;
//                } catch (InterruptedException e) {
//                    Log.e(TAG, "WifiObserverThread Interrupted " + e.getMessage());
//                }
//            }
//        }
//
//        public void setFlag(boolean flag) {
//            this.waitFlag = flag;
//        }
//    }
//
//
//    /**
//     * 主线程，初始化WIFI连接，组播，服务端SOCKET
//     */
//    private class MainThread extends Thread {
//        private InetAddress multiInetAddr;
//        private boolean waitFlag = true;
//        private MulticastSocket socket = null;
//
//        @Override
//        public void run() {
//
//            while (waitFlag) {
//                try {
//                    synchronized (this) {
//                        wait();
//                    }
//                    try {
//                        multicastLock();
//                        //启动多播套接字
//                        socket = new MulticastSocket(MULTICAST_NETWORK_PORT);
//                        multiInetAddr = InetAddress.getByName(MULTICAST_NETWORK_IP);
//                        socket.joinGroup(multiInetAddr);
//                        mMulticastInetAddr = new InetSocketAddress(MULTICAST_NETWORK_IP, MULTICAST_NETWORK_PORT);
//                        socket.setReuseAddress(true);
//                        socket.setLoopbackMode(true);
//                        socket.setTimeToLive(1);
//                        mMulticastSocket = new AppSocket(socket);
//                        mCurrentGroupStatus = GROUP_DISCONNECTED_STATUS;
//                        Log.i(TAG, "MulticastSocket Start Join Group ");
//                    } catch (Exception e) {
//                        Log.e(TAG, "MulticastSocket IO ERROR: ", e);
//                        if (socket != null) {
//                            try {
//                                socket.leaveGroup(multiInetAddr);
//                            } catch (IOException e2) {
//                                e2.printStackTrace();
//                            } finally {
//                                socket.close();
//                            }
//                        }
//                        multicastUnLock();
//                    }
//                    //如果多播网络存在的话
//                    if (isMulticastSocketExisted()) {
//                        try {
//                            multicastSendWorker = new MulticastSendThread();
//                            multicastSendWorker.start();
//                            //启动组网接收线程
//                            multicastRecWorker = new MulticastRecThread();
//                            multicastRecWorker.start();
//                            //监听组网情况的线程
//                            beatWorker = new BeatWorker();
//                            beatWorker.start();
//                            //应答机制的线程
//                            voiceReqWorker = new VoiceReqWorker();
//                            voiceReqWorker.start();
//                            //启动UDP语音包接收线程
//                            udpWorker = new UdpWorker();
//                            udpWorker.start();
//                        } catch (Throwable e) {
//                            e.printStackTrace();
//                        }
//                    }
//                } catch (InterruptedException e) {
//                    Log.e(TAG, "MainThread Interrupted " + e.getMessage());
//                    return;
//                }
//                SystemClock.sleep(5000);
//            }
//        }
//
//        public void close() {
//            if (this.socket != null) {
//                try {
//                    socket.leaveGroup(multiInetAddr);
//                } catch (IOException e1) {
//                    e1.printStackTrace();
//                } finally {
//                    socket.close();
//                }
//            }
//        }
//
//        public void setFlag(boolean flag) {
//            this.waitFlag = flag;
//        }
//    }
//
//    /**
//     * 组网发送线程
//     */
//    private class MulticastSendThread extends Thread {
//        private boolean waitFlag = true;
//
//        @Override
//        public void run() {
//            this.setName(MulticastRecThread.class.getName());
//
//            while (waitFlag) {
//                // 当前的服务端信息是否存在
//                Log.i(TAG, "Multicast Socket Send Start.");
//                Intent intent = new Intent();
//                intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                if (mCurrentGroupStatus != GROUP_CONNECTED_STATUS) {
//                    sendMulticastPacket(getPacketByType(KEY_ACTION_JOIN_REQUEST));
//                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_GROUP_DISCONNECT_STATUS);
//                    sendBroadcast(intent);
//                }
//
//                if (isNetGroupConnected()) {
//                    SystemClock.sleep(WIFI_GROUP_SEND_THREAD_INTERVAL_TIME_1);
//                } else {
//                    SystemClock.sleep(WIFI_GROUP_SEND_THREAD_INTERVAL_TIME);
//                }
//            }
//        }
//
//        public void setFlag(boolean flag) {
//            this.waitFlag = flag;
//        }
//    }
//
//    /**
//     * 组网接收线程
//     */
//    private class MulticastRecThread extends Thread {
//
//        private boolean waitFlag = true;
//        private AUDPPacket packet;
//
//        private void doHandlerInPacket() {
//            int type = SocketUtil.byte2Int(packet.getAction());
//            DatagramPacket inPacket = packet.getPacket();
//            Intent intent;
//            AppUDPPacket outPacket;
//            Log.i(TAG, this.getName() + " receive Data from Remote: " + packet.getSocketAddress());
//            switch (type) {
//                case KEY_ACTION_GROUP_NO_JOIN:
//                    outPacket = (AppUDPPacket) packet.clone();
//                    outPacket.setAction(new byte[]{KEY_ACTION_GROUP_CONFIRM_1});
//                    outPacket.setPacketDataLength(0);
//                    outPacket.setSocketAddress(inPacket.getSocketAddress());
//                    sendMulticastPacket(outPacket);
//                    intent = new Intent();
//                    intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_GROUP_CONNECTING_STATUS);
//                    sendBroadcast(intent);
//                    break;
//                case KEY_ACTION_GROUP_ALLOW_JOIN:
//                    outPacket = (AppUDPPacket) packet.clone();
//                    outPacket.setAction(new byte[]{KEY_ACTION_GROUP_CONFIRM_2});
//                    byte[] dataStr = getDeviceInfoPacket();
//                    outPacket.setPacketDataLength(dataStr.length);
//                    outPacket.setPacketData(dataStr);
//                    outPacket.setSocketAddress(inPacket.getSocketAddress());
//                    sendMulticastPacket(outPacket);
//
//                    mCurrentGroupStatus = GROUP_CONNECTING_STATUS;
//
//                    intent = new Intent();
//                    intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_GROUP_CONNECTING_STATUS);
//                    sendBroadcast(intent);
//
//                    PromptUtil.poolPlay(WIFIService.this, R.raw.wifi_grouping);
//                    break;
//                case KEY_ACTION_GROUP_JOINED:
//                    Log.i(TAG, "Client Device Connected Server");
//
//                    String serverAddress = SocketUtil.convertIntIpAddress(SocketUtil.byte2Int(((InetSocketAddress) inPacket.
//                            getSocketAddress()).getAddress().getAddress()));
//                    if (UDP_SERVER_IP == null || !serverAddress.equals(UDP_SERVER_IP)) {
//                        UDP_SERVER_IP = serverAddress;
//                        //变更服务端地址
//                        mServerAddr = new InetSocketAddress(UDP_SERVER_IP, SERVER_SOCKET_PORT);
//                    }
//                    mCurrentGroupStatus = GROUP_CONNECTED_STATUS;
//                    intent = new Intent();
//                    intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_GROUP_CONNECTED_STATUS);
//                    sendBroadcast(intent);
//                    if (beatWorker != null)
//                        synchronized (beatWorker) {
//                            beatWorker.notify();
//                        }
//                    if (voiceReqWorker != null)
//                        synchronized (voiceReqWorker) {
//                            voiceReqWorker.notify();
//                        }
//
//                    PromptUtil.poolPlay(WIFIService.this, R.raw.wifi_grouped);
//                    break;
//                case KEY_ACTION_GROUP_CHANGE_LANGUAGE_COMPLETE:
//                    intent = new Intent();
//                    intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_LANGUAGE_CHANGED);
//                    sendBroadcast(intent);
//                    break;
//                case KEY_ACTION_DEVICE_RESPONSE:
//                    DeviceInfo deviceInfo = parseDevicePacket((AppUDPPacket) packet);
//                    DevicesInfos.add(deviceInfo);
//                    LogUtil.eee(DevicesInfos.toString());
//                    intent = new Intent();
//                    intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                    intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_HANDLER_DEVICE_INFO);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("DevicesInfos", DevicesInfos);
//                    intent.putExtras(bundle);
//                    sendBroadcast(intent);
//                    break;
//                case KEY_ACTION_DEVICE_CHANGE_RESPONSE_SUCCESS:
//                    LogUtil.eee("名字更改成功");
//                    DeviceInfo successInfo = parseDevicePacket((AppUDPPacket) packet);
//                    for (DeviceInfo info : DevicesInfos) {
//                        if (info.getHostId().equals(successInfo.getHostId())) {
//                            DevicesInfos.remove(info);
//                            DevicesInfos.add(successInfo);
//                            intent = new Intent();
//                            intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                            intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_HANDLER_DEVICE_INFO);
//                            Bundle successBundle = new Bundle();
//                            successBundle.putSerializable("DevicesInfos", DevicesInfos);
//                            intent.putExtras(successBundle);
//                            sendBroadcast(intent);
//                            break;
//                        }
//                    }
//                    break;
//                default:
//                    Log.i(TAG, this.getName() + " UnKown action " + packet.getSocketAddress());
//                    break;
//            }
//        }
//
//        @Override
//        public void run() {
//            this.setName(MulticastRecThread.class.getName());
//            Log.i(TAG, "Multicast Socket Receive Thread Start. ");
//            //客户端组播包 由ID和IP组成
//            while (waitFlag) {
//                try {
//                    packet = mMulticastSocket.receiveMsgFromNetwork(AppSocket.PACKET_BUFFER_SIZE);
//                    if (packet.hasData()) {
//                        doHandlerInPacket();
//                    } else
//                        Log.i(TAG, this.getName() + " receive Data Is Non");
//                } catch (IOException e) {
//                    Log.e(TAG, this.getName() + " Error: ", e);
//                }
//            }
//        }
//
//        public void setFlag(boolean flag) {
//            this.waitFlag = flag;
//        }
//    }
//
//    /**
//     * 用于维护客户端数据传输
//     */
//    public class UdpWorker extends Thread {
//        private boolean waitFlag = true;
//        private AUDPPacket packet;
//        DatagramSocket udpSocket = null;
//
//        public UdpWorker() {
//            this.setName(UdpWorker.class.getName());
//        }
//
//        public boolean isConnected() {
//            return mUdpSocket != null && !mUdpSocket.isClosed();
//        }
//
//        /**
//         * 发送语音包
//         */
//        public synchronized void sendPacketData(byte[] data) throws IOException {
//            sendPacketData(data, 0, data.length);
//        }
//
//        public synchronized void sendPacketData(byte[] data, int offset, int length) throws IOException {
//            if (udpWorker.isConnected()) {
//                AppUDPPacket packet = new AppUDPPacket();
//                packet.setPacketData(data);
//                packet.setPacketDataLength(data.length);
//                packet.setAction(new byte[]{KEY_ACTION_TRANSFER_VOICE_DATA});
//                packet.setSocketAddress(mServerAddr);
//                mUdpSocket.sendMsgToNetwork(packet);
//            } else {
//                throw new IOException("UDP Socket Status is " + mUdpSocket.getSocketInetAddress() + " , Current Wifi Status: " + mCurrentGroupStatus);
//            }
//        }
//
//        public synchronized void sendMeetingData(byte[] data) throws IOException {
//            if (udpWorker.isConnected()) {
//                AppUDPPacket packet = new AppUDPPacket();
//                packet.setPacketData(data);
//                packet.setPacketDataLength(data.length);
//                packet.setAction(new byte[]{KEY_ACTION_CREATE_MEETING});
//                packet.setSocketAddress(mServerAddr);
//                mUdpSocket.sendMsgToNetwork(packet);
//            } else {
//                throw new IOException("UDP Socket Status is " + mUdpSocket.getSocketInetAddress() + " , Current Wifi Status: " + mCurrentGroupStatus);
//            }
//        }
//
//        @Override
//        public void run() {
//            while (waitFlag) {
//                try {
//                    udpSocket = new DatagramSocket(new InetSocketAddress(
//                            UDP_CLIENT_IP, CLIENT_SOCKET_PORT));
//                } catch (SocketException e) {
//                    e.printStackTrace();
//                }
//                if (udpSocket != null) {
//                    mUdpSocket = new AppSocket(udpSocket);
//                    //客户端组播包 由ID和IP组成
//                    while (waitFlag && mUdpSocket.isBound()) {
//                        try {
//                            packet = mUdpSocket.receiveMsgFromNetwork(AppSocket.PACKET_BUFFER_SIZE);
//                            Log.i(TAG, this.getName() + " Starting Rec Voice Transfer..===================================================");
//                            if (packet.hasData()) {
//                                Log.i(TAG, this.getName() + " Receive Data from Remote: "
//                                        + ((InetSocketAddress) packet.getSocketAddress()).getHostName());
//                                int action = SocketUtil.byte2Int(packet.getAction());
//                                switch (action) {
//                                    case KEY_ACTION_TRANSFER_VOICE_DATA:
//                                        mWifiObserver.doWhat(packet);
//                                        break;
//                                    case KEY_ACTION_CREATE_MEETING_RESPONSE:
//                                        LogUtil.eee("receive create meeting response====================================");
//                                        Intent intent = new Intent();
//                                        intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                                        intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_HANDLER_MEETING_CREATED);
//                                        mMeetingInfo = MeetingInfo.parse(new String(((AppUDPPacket) packet).getPacketData()));
//                                        intent.putExtra(KEY_HANDLER_MEETING_CREATED, mMeetingInfo);
//                                        sendBroadcast(intent);
//                                }
//                            } else
//                                Log.i(TAG, this.getName() + " receive Data Is Null or Length 0");
//                        } catch (Exception e) {
//                            Log.e(TAG, this.getName() + " Error: ", e);
//                        }
//                    }
//                }
//                SystemClock.sleep(10000);
//            }
//        }
//
//        public void setFlag(boolean flag) {
//            this.waitFlag = flag;
//        }
//    }
//
//    /**
//     * WIFI观察者
//     */
//    public class WIFIObserver {
//
//        public void doWhat(Object... args) {
//            //播放语音
//            AppUDPPacket packet = (AppUDPPacket) args[0];
//            String msg = new String(packet.getPacketData());
//            LogUtil.eee("receiver translated msg from the M-Master：" + msg);
//            VoiceInfo voiceInfo = VoiceInfo.parse(msg);
//            Intent intent = new Intent();
//            intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//            if (!TextUtils.isEmpty(voiceInfo.getTranContent())) {
//                intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_HANDLER_ORG_VOICE_DATA);
//                intent.putExtra(INTENT_TRANSFER_VOICE_DATA, voiceInfo);
//            } else {
//                intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_HANDLER_ORG_VOICE_TEXT_ERROR);
//            }
//            sendBroadcast(intent);
//
//            //在数据库中保存聊天记录
//            ContentResolverUtil resolverUtil = new ContentResolverUtil(WIFIService.this);
//            int id = resolverUtil.insertChatHistory(voiceInfo, mMeetingInfo);
//            if (id <= 0) {
//                LogUtil.e("insert data to database not successfully");
//            }
//        }
//    }
//
//    /**
//     * 用于检查组网状况，每隔一段时间socket发送消息给server
//     */
//    class BeatWorker extends Thread {
//        private boolean waitFlag = true;
//        private AUDPPacket inPacket;
//        private SocketAddress beatAddr;
//        private int disconnectionCount = 0;
//        private DatagramSocket udpSocket = null;
//
//        public BeatWorker() {
//            this.setName(BeatWorker.class.getName());
//        }
//
//        public boolean isConnected() {
//            return mBeatSocket != null && !mBeatSocket.isClosed();
//        }
//
//        /**
//         * 发送语音包
//         */
//        public synchronized void sendPacketData(byte[] data) throws IOException {
//            sendPacketData(data, 0, data.length);
//        }
//
//        public synchronized void sendPacketData(byte[] data, int offset, int length) throws IOException {
//            if (isConnected()) {
//                AppUDPPacket packet = new AppUDPPacket();
//                packet.setPacketData(data);
//                packet.setPacketDataLength(data.length);
//                packet.setAction(new byte[]{KEY_ACTION_GROUP_CONNECTED_REQUEST});
//                packet.setSocketAddress(beatAddr);
//                mBeatSocket.sendMsgToNetwork(packet);
//            } else {
//                LogUtil.eee("UDP Socket Status is " + mBeatSocket.getSocketInetAddress() + " , Current Wifi Status: " + mCurrentGroupStatus);
//            }
//        }
//
//        @Override
//        public void run() {
//            try {
//                while (!Thread.interrupted()) {
//                    synchronized (this) {
//                        while (mCurrentGroupStatus != GROUP_CONNECTED_STATUS) {
//                            wait();
//                        }
//                    }
//                    Log.i(TAG, "BeatWorker Thread Start. ");
//                    beatAddr = new InetSocketAddress(UDP_SERVER_IP, SERVER_SOCKET_PORT_BEAT);
//                    if (mBeatSocket == null) {
//                        try {
//                            udpSocket = new DatagramSocket(new InetSocketAddress(
//                                    UDP_CLIENT_IP, CLIENT_SOCKET_PORT_BEAT));
//                            udpSocket.setSoTimeout(5000);
//                            mBeatSocket = new AppSocket(udpSocket);
//                        } catch (IOException e) {
//                            Log.e(TAG, "", e);
//                        }
//                    }
//                    if (mBeatSocket != null) {
//                        while (waitFlag && mBeatSocket.isBound()) {
//                            try {
//                                byte[] dataStr = getDeviceInfoPacket();
//                                sendPacketData(dataStr);
//                                try {
//                                    inPacket = mBeatSocket.receiveMsgFromNetwork(AppSocket.PACKET_BUFFER_SIZE);
//                                    if (inPacket.hasData()) {
//                                        Log.i(TAG, this.getName() + " receive Data from Remote: "
//                                                + inPacket.getSocketAddress());
//                                        int type = SocketUtil.byte2Int(inPacket.getAction());
//                                        switch (type) {
//                                            case KEY_ACTION_GROUP_CONNECTED_RESPONSE:
//                                                disconnectionCount = 0;
//                                                break;
//                                        }
//                                    } else {
//                                        Log.i(TAG, this.getName() + "no data received");
//                                    }
//                                } catch (SocketTimeoutException e) {
//                                    disconnectionCount++;
//                                    Log.i(TAG, "socket timeout when beat");
//                                }
//                                if (disconnectionCount >= 5) {
//                                    mCurrentGroupStatus = GROUP_DISCONNECTED_STATUS;
//                                    disconnectionCount = 0;
//                                    break;
//                                }
//                            } catch (Exception e) {
//                                Log.e(TAG, this.getName() + " Error: ", e);
//                            } finally {
//                                SystemClock.sleep(WIFI_GROUP_SEND_THREAD_INTERVAL_TIME);
//                            }
//                        }
//                    }
//                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//
//        public void setFlag(boolean flag) {
//            this.waitFlag = flag;
//        }
//    }
//
//    /**
//     * 用于维护客户端数据传输
//     */
//    class VoiceReqWorker extends Thread {
//        private boolean waitFlag = true;
//        private AUDPPacket inPacket;
//        private SocketAddress voiceReqAddr;
//        private DatagramSocket udpSocket = null;
//        private boolean isReqPermitted = false;
//        private boolean isReqStop = false;
//        private boolean isReqStart = false;
//
//
//        public VoiceReqWorker() {
//            this.setName(VoiceReqWorker.class.getName());
//        }
//
//        public boolean isConnected() {
//            return mVoiceReqSocket != null && !mVoiceReqSocket.isClosed();
//        }
//
//        /**
//         * 发送语音包
//         */
//        public synchronized void sendPacketData(byte[] data, int action) throws IOException {
//            sendPacketData(data, 0, data.length, action);
//        }
//
//        public synchronized void sendPacketData(byte[] data, int offset, int length, int action) throws IOException {
//            if (isConnected()) {
//                AppUDPPacket packet = new AppUDPPacket();
//                packet.setPacketData(data);
//                packet.setPacketDataLength(data.length);
//                if (action == 1) {
//                    packet.setAction(new byte[]{KEY_ACTION_VOICE_REQUEST_START});
//                } else if (action == 2) {
//                    packet.setAction(new byte[]{KEY_ACTION_VOICE_REQUEST_STOP});
//                } else if (action == 3) {
//                    packet.setAction(new byte[]{KEY_ACTION_VOICE_REQUEST_PERSIST});
//                }
//
//                packet.setSocketAddress(voiceReqAddr);
//                mVoiceReqSocket.sendMsgToNetwork(packet);
//            } else {
//                LogUtil.eee("UDP Socket Status is " + mVoiceReqSocket.getSocketInetAddress() + " , Current Wifi Status: " + mCurrentGroupStatus);
//            }
//        }
//
//        public void requestStop() {
//            isReqPermitted = false;
//        }
//
//        @Override
//        public void run() {
//            try {
//                while (!Thread.interrupted() && waitFlag) {
//                    synchronized (this) {
//                        while (mCurrentGroupStatus != GROUP_CONNECTED_STATUS) {
//                            wait();
//                        }
//                    }
//                    Log.i(TAG, "VoiceReqWorker Thread Start. ");
//                    voiceReqAddr = new InetSocketAddress(UDP_SERVER_IP, SERVER_SOCKET_PORT_VOICE_REQUEST);
//
//                    if (mVoiceReqSocket == null) {
//                        try {
//                            udpSocket = new DatagramSocket(new InetSocketAddress(
//                                    UDP_CLIENT_IP, CLIENT_SOCKET_PORT_VOICE_REQUEST));
//                            udpSocket.setSoTimeout(1500);
//                            mVoiceReqSocket = new AppSocket(udpSocket);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    if (mVoiceReqSocket != null) {
//                        while (waitFlag && mVoiceReqSocket.isBound()) {
//                            try {
//                                int action = voiceReqQueue.take();
//                                if (action == 1) {
//                                    isReqStart = true;
//                                }
//                                if (action == 2) {
//                                    isReqStop = true;
//                                }
//                                // TODO: 2016/4/21 处理action
//                                Intent intent = new Intent();
//                                intent.setAction(Constants.WIFI_BORADCAST_ACTION);
//                                if (mCurrentGroupStatus == GROUP_CONNECTED_STATUS) {
//                                    while (isReqPermitted || isReqStart || isReqStop) {
//                                        isReqStart = false;
//                                        isReqStop = false;
//                                        /*String dataStr = getDeviceInfoPacket();
//                                        sendPacketData(dataStr.getBytes(), action);*/
//                                        sendPacketData(new byte[0], action);
//                                        LogUtil.eee("input input input input ...............");
//                                        try {
//                                            inPacket = mVoiceReqSocket.receiveMsgFromNetwork(AppSocket.PACKET_BUFFER_SIZE);
//                                            if (inPacket.hasData()) {
//                                                Log.i(TAG, this.getName() + " receive Data from Remote: "
//                                                        + inPacket.getSocketAddress());
//                                                int type = SocketUtil.byte2Int(inPacket.getAction());
//                                                switch (type) {
//                                                    case KEY_ACTION_VOICE_RESPONSE_PERMIT:
//                                                        intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_PERMIT);
//                                                        isReqPermitted = true;
//                                                        action = 3;
//                                                        sendBroadcast(intent);
//                                                        break;
//                                                    case KEY_ACTION_VOICE_RESPONSE_PREVENT:
//                                                        intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_PREVENT);
//                                                        isReqPermitted = false;
//                                                        sendBroadcast(intent);
//                                                        break;
//                                                    case KEY_ACTION_VOICE_RESPONSE_FINISH:
//                                                        intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_FINISH);
//                                                        isReqPermitted = false;
//                                                        sendBroadcast(intent);
//                                                        break;
//                                                    case KEY_ACTION_VOICE_RESPONSE_PERSIST:
//                                                        LogUtil.eee("voice input persist.......");
//                                                        break;
//                                                }
//                                            } else {
//                                                Log.i(TAG, this.getName() + "no data received");
//                                                isReqPermitted = false;
//                                            }
//                                        } catch (SocketTimeoutException e) {
//                                            Log.i(TAG, "socket timeout when beat");
//                                            intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_PREVENT);
//                                            isReqPermitted = false;
//                                            sendBroadcast(intent);
//                                        }
//                                        SystemClock.sleep(500);
//                                    }
//                                } else {
//                                    if (isReqStart) {
//                                        intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_PREVENT);
//                                        isReqStart = false;
//                                        sendBroadcast(intent);
//                                    } else if (isReqStop) {
//                                        intent.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_VOICE_RESPONSE_FINISH);
//                                        isReqStop = false;
//                                        sendBroadcast(intent);
//                                    }
//                                }
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            } catch (Exception e) {
//                                Log.e(TAG, this.getName() + " Error: ", e);
//                            }
//                        }
//                    }
//                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//
//        public void setFlag(boolean flag) {
//            this.waitFlag = flag;
//        }
//
//        public void close() {
//            if (mVoiceReqSocket != null) {
//                mVoiceReqSocket.close();
//            }
//        }
//    }
//
//    /**
//     * 网络状态广播
//     */
//    private class NetReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
//            WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
//            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
//                if (networkInfo != null && networkInfo.isConnected()) {
//                    ///网络连接
//                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//                        //wifi连接
//                        LogUtil.eee("NET_TYPE_WIFI");
//                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
//                        //有线网络
//                        LogUtil.eee("NET_TYPE_ETHERNET");
//                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
//                        //3g网络
//                        LogUtil.eee("NET_TYPE_MOBILE");
//                    }
//                } else if (networkInfo != null && networkInfo.isAvailable()) {
//                    //有网络，但是没有连接
//                    LogUtil.eee("NET_TYPE_AVAILABLE");
//                } else {
//                    //其他状态
//                    LogUtil.eee("NET_TYPE_NOT_AVAILABLE");
//                }
//            } else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
//                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
//                switch (wifiState) {
//                    case WifiManager.WIFI_STATE_DISABLED:
//                        LogUtil.e("WifiState", "DISABLED");
//                        mCurrentWifiStatus = WIFI_DISABLED_STATUS;
//                        mCurrentGroupStatus = GROUP_WIFI_NOT_CORRECT_STATUS;
//                        try {
//                            netObserverQueue.put(0);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        break;
//                    case WifiManager.WIFI_STATE_DISABLING:
//                        break;
//                    case WifiManager.WIFI_STATE_ENABLED:
//                        LogUtil.e("WifiState", "ENABLED");
//                        mCurrentWifiStatus = WIFI_ENABLED_STATUS;
//                        break;
//                    case WifiManager.WIFI_STATE_ENABLING:
//                        break;
//                    case WifiManager.WIFI_STATE_UNKNOWN:
//                        break;
//                }
//            } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
//                Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
//                if (null != parcelableExtra) {
//                    NetworkInfo info = (NetworkInfo) parcelableExtra;
//                    switch (info.getState()) {
//                        case CONNECTED:
//                            // 网络已连接
//                            LogUtil.e("WifiState", "CONNECTED");
//                            mCurrentWifiStatus = WIFI_CONNECTED_STATUS;
//                            if (wifiInfo.getSSID() != null && (wifiInfo.getSSID().equalsIgnoreCase("\"" + UNIQUE_SSID + "\"") || wifiInfo.getSSID().equalsIgnoreCase(UNIQUE_SSID))) {
//                                LogUtil.e("WifiState", "CORRECT");
//                                mCurrentWifiStatus = WIFI_CORRECT_STATUS;
//                                WIFIService.this.networkInfo = mConnectivityManager.getActiveNetworkInfo();
//                                String currentIp = SocketUtil.convertIntIpAddress(wifiInfo.getIpAddress());
//                                if (currentIp != null && !currentIp.equals(UDP_CLIENT_IP)) {
//                                    UDP_CLIENT_IP = currentIp;
//                                    LogUtil.eee("UDP_CLIENT_IP=" + UDP_CLIENT_IP);
//                                }
//                                try {
//                                    netObserverQueue.put(1);
//                                } catch (InterruptedException e) {
//                                    e.printStackTrace();
//                                }
//
//                                Intent intent1 = new Intent();
//                                intent1.setAction(Constants.WIFI_BORADCAST_ACTION);
//                                intent1.putExtra(Constants.BORADCAST_INTENT_OPTION, KEY_HANDLER_WIFI_CONNECT);
//                                sendBroadcast(intent1);
//                            } else {
//                                //连接的不是制定的网络
//                                LogUtil.e("WifiState", "INCORRECT");
//                                mCurrentWifiStatus = WIFI_INCORRECT_STATUS;
//                                mCurrentGroupStatus = GROUP_WIFI_NOT_CORRECT_STATUS;
//                                try {
//                                    netObserverQueue.put(2);
//                                } catch (InterruptedException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                            break;
//                        case CONNECTING:
//                            LogUtil.e("WifiState", "CONNECTING");
//                            break;
//                        case DISCONNECTED:
//                            LogUtil.e("WifiState", "DISCONNECTED");
//                            mCurrentWifiStatus = WIFI_DISCONNECTED_STATUS;
//                            mCurrentGroupStatus = GROUP_WIFI_NOT_CORRECT_STATUS;
//                            try {
//                                netObserverQueue.put(0);
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                            break;
//                        case DISCONNECTING:
//                            LogUtil.e("WifiState", "DISCONNECTING");
//                            break;
//                        case SUSPENDED:
//                            LogUtil.e("WifiState", "SUSPENDED");
//                            break;
//                        case UNKNOWN:
//                            LogUtil.e("WifiState", "UNKNOWN");
//                            break;
//                        default:
//                            break;
//                    }
//                }
//            }
//        }
//    }
//}
